//
//  NetworkTools.swift
//  SwiftNetworkRequestEncapsulation
//
//  Created by 黄亦寒 on 16/9/20.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求类型
enum RequestType{
    case GET
    case POST
}

class NetworkTools: AFHTTPSessionManager {

    //给回调闭包定义别名
    typealias CallBackType = (Any?,Error?)->()
    
    static let sharedTools:NetworkTools = {
        let tools = NetworkTools()
        //增加接收数据的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    //网络请求方法
    func request(type:RequestType,url:String,param:Any?,callBack:@escaping CallBackType) {
        if type == .GET {
            get(url, parameters: param, progress: nil, success: { (_, response) in
                callBack(response,nil)
                }, failure: { (_, error) in
                    callBack(nil,error)
            })
        }else{
           post(url, parameters: param, progress: nil, success: { (_, response) in
            callBack(response,nil)
            }, failure: { (_, error) in
                callBack(nil,error)
           })
        }
        
        
        
    }
}

//OAuth登录相关的接口
extension NetworkTools{
//根据code获取accessToken
    func requestAccessToken(code:String,callBack:@escaping CallBackType) {
        //请求接口的地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //请求需要的参数
        let params = ["client_id":AppKey,
                      "client_secret":AppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":Redirect_Uri
                      ]
        //使用封装好的网络请求
        request(type: .POST, url: url, param: params, callBack: callBack)
        
        
    }
    
//通过令牌取到用户信息
    func requestUserInfo(accessToken:String,uid:Int,callBack:@escaping CallBackType) -> Void {
        //请求地址
        let url = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let params:[String:Any] = ["access_token":accessToken,
                      "uid":uid
                      ]
        
        
        request(type: .GET, url: url, param: params, callBack: callBack)
    }
    

}

//获取微博首页关注用户数据的方法
extension NetworkTools {
    
    func requestStatuses(accessToken:String,maxId:Int64,sinceId:Int64, callBack:@escaping CallBackType) -> Void {
        //请求地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //请求参数
        let params:[String:Any] = ["access_token":accessToken,
                                   "max_id":maxId,
                                   "sinceId":sinceId
        ]
        //print("---\(accessToken)")
        //发送请求
        request(type: .GET, url: url, param: params, callBack: callBack)
        
    }
}

//发送微博的接口
extension NetworkTools {
    //发送文字微博的借口
    func update(accessToken:String,status:String,callBack:@escaping CallBackType) -> Void {
        //接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //参数
        let params = [
            "access_token":accessToken,
            "status":status
        ]
        //发送请求
        request(type: .POST, url: url, param: params, callBack: callBack)
    }
    
    //发送文字微博加配图的接口
    func upload(accessToken:String,status:String,image:UIImage,callBack:@escaping CallBackType) -> Void {
        //接口地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //参数
        let params = [
            "access_token":accessToken,
            "status":status
        ]
        
        //把图片转为二进制数据
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        //上传请求
        post(url, parameters: params, constructingBodyWith: { (formData) in
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            }, progress: nil, success: { (_, response) in
                callBack(response,nil)
            }) { (_, error) in
                callBack(nil,error)
        }
        
    }
}
